package mipushdemo.xiaomi.com.diyitonghang.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import mipushdemo.xiaomi.com.diyitonghang.R;
import mipushdemo.xiaomi.com.diyitonghang.api.ApiService;
import mipushdemo.xiaomi.com.diyitonghang.data.bean.BaseChannelItem;
import mipushdemo.xiaomi.com.diyitonghang.data.bean.HuaBean;
import mipushdemo.xiaomi.com.diyitonghang.ui.adapter.AdapterlistBaseChannelItem;
import mipushdemo.xiaomi.com.diyitonghang.ui.adapter.HuaRecyAdapter;
import mipushdemo.xiaomi.com.diyitonghang.ui.fragment.home.InfoActivity;
import mipushdemo.xiaomi.com.diyitonghang.ui.fragment.home.SearchDataActivity;
import mipushdemo.xiaomi.com.diyitonghang.utils.RetrofitUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HuatiFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HuatiFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HuatiFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private RecyclerView ryChannel;

    public HuatiFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HuatiFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HuatiFragment newInstance(String param1, String param2) {
        HuatiFragment fragment = new HuatiFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View inflate = LayoutInflater.from(this.getActivity()).inflate(R.layout.fragment_huati, null);
        ryChannel = (RecyclerView) inflate.findViewById(R.id.ryChannel);

        initView2(inflate);

        return inflate;
    }
    private void initView2(View inflate) {
        //拼接json字符串
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("keyword", SearchDataActivity.title);
            jsonObject.put("cursor", "0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String s = jsonObject.toString();
        String header = "application/json";
        RequestBody requestBody = RequestBody.create(MediaType.parse(header), s);
        ApiService apiService = RetrofitUtils.newInstance().netWorkRequest();
        Observable<HuaBean> observable = apiService.topicSearch(header, requestBody);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HuaBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HuaBean huaBean) {
                        final List<HuaBean.DataBean.TopicListBean> mData = huaBean.getData().getTopicList();
                        ryChannel.setLayoutManager(new LinearLayoutManager(getContext()));
                        HuaRecyAdapter adapter = new HuaRecyAdapter(R.layout.one_home_item, mData);
                        ryChannel.setAdapter(adapter);
                        View view = LayoutInflater.from(getContext()).inflate(R.layout.null_item, null);
                        adapter.setEmptyView(view);

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("Error222",e.getMessage()+"=="+e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }




    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
